/* eslint-disable no-nested-ternary */
/* eslint-disable react/prop-types */
/* eslint-disable no-console */
import React, { useState, useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';
import exceed from 'utils/apimap';
import { Message } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import moment from 'moment';
import { navigateOpen } from 'utils/router';
import BillingModal from './billingModal';
import intl from '../../locale';

const Target = (props) => {
  const modalRoot = document.querySelector('.enterprise-setting__main__content');
  const eleRef = useRef(document.createElement('div'));

  useEffect(() => {
    if (modalRoot) {
      modalRoot.style.overflow = 'hidden';
      modalRoot.scrollTop = '0px';
      modalRoot.appendChild(eleRef.current);
      return () => {
        if (modalRoot) {
          modalRoot.style.overflow = 'auto';
          modalRoot.removeChild(eleRef.current);
        }
      };
    }
  }, [modalRoot]);
  return ReactDOM.createPortal(<div>{props.children}</div>, eleRef.current);
};

const BillingHander = ({ visi, status, biObj, isClose, billingOpenHander }) => {
  const [visible, setViseble] = useState(visi);
  //
  useEffect(() => {
    const localValue = window.localStorage.getItem(`codeBillinglimit-${window.config.orgId}`);
    const dataValue = moment().format('YYYY/MM/DD');
    const billingVisible = localValue
      ? JSON.parse(localValue).filter((va) => va === dataValue)
      : [];
    const limitstatus = status === 'limit' && billingVisible.length > 0;
    if (limitstatus) {
      setViseble(false);
    }
  }, [status, isClose, biObj]);

  const setVisibleCallback = () => {
    setViseble(false);
  };
  //
  const advancedBuyUrl = () => {
    // const version = tools.getCookie('version') === 'ga' ? 'pre-' : '';
    navigateOpen(
      `https://devops.aliyun.com/org-admin/${
        window.config && window.config.orgId
      }/profile?buy=true`,
    );

    if (isClose || !status) {
      typeof isClose === 'function' && isClose && isClose();
      // window.TB_NAVIGATION_CONFIG.lockquery.open({ visible: false });
      // setVisibleCallback();
    }
  };
  const handleEnter = async () => {
    const value = await exceed.fetch({
      api: 'organization.buyOrgPlan',
      params: { orgId: window.FORCE.organization.id },
      data: { order_plan_type: 'trial' },
    });

    if (value) {
      Message.success({
        title: intl.get({
          id: 'code-assets.components.billing.TheOrderHasBeenActivated',
          defaultMessage: '订单开通成功',
        }),
        duration: 1000,
      });

      billingOpenHander && (await billingOpenHander());
      typeof isClose === 'function' && isClose && isClose();
      // window.TB_NAVIGATION_CONFIG.lockquery.open({ visible: false });
      setVisibleCallback();
    }
    // !status && window.TB_NAVIGATION_CONFIG.lockquery.open({ visible: false });
  };
  const closeFn = async () => {
    if (status === 'limit') {
      const localValue = window.localStorage.getItem(`codeBillinglimit-${window.config.orgId}`);
      const setValue = localValue ? JSON.parse(localValue) : [moment().format('YYYY/MM/DD')];
      // eslint-disable-next-line no-unused-expressions
      localValue ? setValue.push(moment().format('YYYY/MM/DD')) : null;
      window.localStorage.setItem(
        `codeBillinglimit-${window.config.orgId}`,
        JSON.stringify(setValue),
      );
    }
    billingOpenHander && (await billingOpenHander());
    typeof isClose === 'function' && isClose && isClose();
    // window.TB_NAVIGATION_CONFIG.lockquery.open({ visible: false });
    setVisibleCallback();
  };
  const titleHander = () => {
    if (status !== 'normal') {
      return '升级套餐继续体验云效·Codeup';
    }
    const value =
      biObj && biObj.order_info && biObj.order_info.end_date
        ? moment(biObj.order_info.end_date).diff(moment(), 'day')
        : 0;
    return <React.Fragment>{value < 0 && '升级套餐继续体验云效·Codeup'}</React.Fragment>;
  };

  const reasonText = () => {
    const value =
      biObj && biObj.order_info && biObj.order_info.end_date
        ? moment(biObj.order_info.end_date).diff(moment(), 'day')
        : 0;
    // eslint-disable-next-line no-nested-ternary
    const type =
      biObj && biObj.order_info && biObj.order_info.plan_type === 'commonbuy'
        ? intl.get({ id: 'code-assets.components.billing.Order', defaultMessage: '订单' })
        : biObj && biObj.order_info && biObj.order_info.plan_type === 'trial'
        ? intl.get({ id: 'code-assets.components.billing.FreeTrial', defaultMessage: '免费试用' })
        : intl.get({ id: 'code-assets.components.billing.Order', defaultMessage: '订单' });

    const dateValue =
      biObj &&
      biObj.order_info &&
      biObj.order_info.end_date &&
      moment(biObj.order_info.end_date).format('YYYY/MM/DD');
    if (value < 0) {
      return (
        <span style={{ color: '#777777', fontSize: 14 }}>
          <YunxiaoIcon type="warning-fill" style={{ marginRight: 5, fontSize: 20 }} />
          {dateValue}
          {type}
          {intl.get({ id: 'code-assets.components.billing.Expired', defaultMessage: '已到期' })}
        </span>
      );
    }
    if (status === 'limit') {
      return (
        <span>
          <YunxiaoIcon type="warning-fill" style={{ color: 'ffb96e', marginRight: '10px' }} />
          企业人数已超额，请尽快升级套餐
        </span>
      );
    }
    if (status === 'strictLimit') {
      return (
        <span>
          <YunxiaoIcon
            type="delete-fill"
            style={{ color: 'rgb(237, 103, 90)', marginRight: '10px' }}
          />
          企业人数已超额，无法继续使用服务，请升级套餐
        </span>
      );
    }
  };

  // const winSdkLock = () => {
  //   window.TB_NAVIGATION &&
  //     window.TB_NAVIGATION.ready(() => {
  //       window.TB_NAVIGATION_CONFIG.lockquery.open &&
  //         window.TB_NAVIGATION_CONFIG.lockquery.open({
  //           visible,
  //           title:
  //             biObj && biObj.is_can_use_trial_feature ? 'Codeup 邀请您免费体验' : titleHander(),
  //           desc: '「代码安全」针对企业代码仓库安全风险提供了一系列风控措施，包括事前监测、事中通知、事后审计全面管控，支持邮件、站内信与钉钉多种触达方式，帮助管理员在风险事件发生时快速采取应对措施，降低损失和风险。',
  //           trialOrder: moment(biObj && biObj.order_info && biObj.order_info.end_date).format(
  //             'YYYY.MM.DD',
  //           ), // 日期到期时间
  //           closeFn, // 稍后处理hander
  //           descMoreUrl:
  //             'https://thoughts.aliyun.com/sharespace/5e8c37eb546fd9001aee8242/folders/5fe1ba3f20764b001fa6b723', // 了解更多的链接
  //           cancelClick: '', // dialog 关闭事件
  //           lock: status || 'normal', // normal:正常 limit:软锁 strictLimit:硬锁
  //           isAdmin: true, // 管理员
  //           isEndTrial: biObj && biObj.is_has_used_trial_feature, // 暂时不知道是干啥的
  //           premiumVersion: '', // 暂时不知道是干啥的 baseVersion:普通版, bonusVersion:福利包版, premiumVersion:付费版
  //           orgId: window.config && window.config.orgId,
  //           handleEnter, // 立即开通事件
  //           advancedBuyUrl, // 升级套餐的url
  //         });
  //     });
  // };
  return (
    <React.Fragment>
      {/* {
         winSdkLock()
        } */}
      <Target>
        <BillingModal
          visible={visible}
          title={
            biObj && biObj.is_can_use_trial_feature ? '云效·Codeup 邀你免费体验' : titleHander()
          }
          desc={intl.get({
            id: 'code-assets.components.billing.CodeSecurityProvidesASeries',
            defaultMessage:
              '「代码安全」针对企业代码仓库安全风险提供了一系列风控措施，包括事前监测、事中通知、事后审计全面管控，支持邮件、站内信与钉钉多种触达方式，帮助管理员在风险事件发生时快速采取应对措施，降低损失和风险。',
          })}
          reasonText={reasonText()}
          trialOrder={moment(biObj && biObj.order_info && biObj.order_info.end_date).format(
            'YYYY.MM.DD',
          )}
          closeFn={closeFn}
          descMoreUrl="https://help.aliyun.com/document_detail/153808.html"
          cancelClick=""
          lock={status || 'normal'}
          isAdmin
          isEndTrial={biObj && biObj.is_has_used_trial_feature}
          premiumVersion=""
          orgId={window.config && window.config.orgId}
          handleEnter={handleEnter}
          advancedBuyUrl={advancedBuyUrl}
        />
      </Target>
    </React.Fragment>
  );
};

export default BillingHander;
